package com.atguigu.chapter07.a_window;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;

/**
 * @ClassName: Flink01_Tumbling_Window
 * @Description:
 * @Author: kele
 * @Date: 2021/4/6 20:06
 *
 * reduce：输入的函数类型必须要和输出的函数类型一致
 *
 **/
public class Flink06_Window_Reduce_Function {

    public static void main(String[] args) {

        Configuration conf = new Configuration();
        conf.setInteger("rest.port",20000);

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(2);

        DataStreamSource<String> ds = env.socketTextStream("hadoop162", 8888);

        ds.flatMap(new FlatMapFunction<String, Tuple2<String,Long>>() {
            @Override
            public void flatMap(String line, Collector<Tuple2<String, Long>> out) throws Exception {

                for (String word : line.split(" ")) {
                    out.collect(Tuple2.of(word,1l));
                }
            }
        })
                .keyBy(d -> d.f0)
             .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))

                //返回值的数据类型和输入的数据类型一致
                .reduce(new ReduceFunction<Tuple2<String, Long>>() {
                    @Override
                    public Tuple2<String, Long> reduce(
                                    Tuple2<String, Long> value1,
                                    Tuple2<String, Long> value2) throws Exception {
                        //第一个进入的元素不处理
                        System.out.println("reduce...");

                        return Tuple2.of(value1.f0,value1.f1+value2.f1);

                    }
                })
                .print();


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}
